/**
 * 图片预览
 * @param urls url列表
 * @param current 当前显示下标
 */
export function previewImage(urls, current = 0) {
  uni.previewImage({ urls, current, complete: complete => console.log('previewImage complete', complete) })
}

/**
 * 拨打电话
 * @param phoneNumber 电话号码
 */
export function makePhoneCall(phoneNumber) {
  uni.makePhoneCall({
    phoneNumber,
    fail: () => new Promise(() => { }),
    complete: complete => console.log('makePhoneCall complete', complete),
  })
}

/** 打开另一个小程序 */
export function navigateToMiniProgram(appId, path = '/pages/index/index', extraData = {}) {
  uni.navigateToMiniProgram({ appId, path, extraData })
}

/** 退出程序 */
export function exitMiniProgram() {
  uni.exitMiniProgram({ complete: complete => console.log('exitMiniProgram complete', complete) })
}

/**
 * 订阅消息
 * @param tmplIds 消息模板ID
 * @returns
 */
export function requestSubscribeMessage(tmplIds): any {
  return new Promise((resolve, reject) => {
    uni.requestSubscribeMessage({
      tmplIds,
      success: res => resolve(res),
      fail: err => reject(err),
    })
  })
}

/**
 * 系统剪贴板
 * @param value 内容
 */
export function setClipboardData(value) {
  uni.setClipboardData({
    data: value,
    success: () => showToast('复制成功'),
    complete: complete => console.log('setClipboardData complete', complete),
  })
}

/**
 * 消息提示
 * @param title 内容
 * @param duration 显示时间
 */
export function showToast(title, duration = 2000) {
  uni.showToast({ title, icon: 'none', mask: true, duration })
  return sleep(duration)
}

/**
 * @description 获取当前页面
 */
export function getPage() {
  const pages = getCurrentPages()
  return pages[pages.length - 1]
}

/**
 * 文件下载
 * @param url 下载资源的 url
 * @returns
 */
export function downloadFile(url) {
  return uni.downloadFile({ url })
}

/**
 * 获取图片信息
 * @param src 资源的 url
 * @returns
 */
export function getImageInfo(src) {
  return uni.getImageInfo({ src })
}

/**
 * 微信小程序支付
 * @param params
 * @param params.provider 服务提供商
 * @param params.orderInfo 订单数据
 * @param params.payment 订单数据
 * @returns
 */
export function wxpay_payment(params: { provider, orderInfo, payment?: any }) {
  return new Promise((reslove, reject) => {
    let data = {}
    if (params.payment) {
      const { appId, nonceStr, packageValue, paySign, signType, timeStamp } = params.payment
      data = { appId, timeStamp, nonceStr, package: packageValue, signType, paySign }
    }
    uni.requestPayment({
      provider: params.provider,
      orderInfo: params.orderInfo,
      ...data,
      success: (res) => {
        console.log('订单支付', res)
        reslove(res)
      },
      fail(err) {
        console.log('订单支付失败', err)
        showToast('支付失败')
        reject(err)
      },
    })
  })
}
